import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.anyline.pdf.util.PDFUtil;
import org.anyline.util.ImgUtil;
import org.anyline.util.regular.RegularUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class InvoiceParse {
    public static String decode(File file) {
        String code = null;
        String format = "JPEG";
        String name = file.getName().toUpperCase();
        if(name.endsWith("PDF")){
            format = "PDF";
        }else if(name.endsWith("PNG")){
            format = "PNG";
        }
        if(format.equals("PDF")){
            String txt = PDFUtil.read(file);
            System.out.println("发票内容:"+txt);
            code = RegularUtil.cut(txt, "发票号码:", "\n");
        }else{
            try {
                String txt = read(file);
                System.out.println("二维码内容:"+txt);
                code = txt.split(",")[3];
            }catch (Exception ignored){}
        }
        return code;
    }

    public static String read(File img) {
        String content = null;
        BufferedImage image;
        int height = 0;
        try {
            image = ImageIO.read(img);
            height = image.getHeight();
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap bits = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bits, hints);//解码
            content = result.getText();
        } catch (Exception e) {
            //如果解析不出来，把图片截取左上部分(注意二维码是不是在左上),一直截取到150像素
            if(height > 300) {
                try {
                    File tmp = new File("tmp_"+img.getName());
                    ImgUtil.cut(img, tmp,0, 0, height / 2, height / 2);
                    content = read(tmp);
                    tmp.delete();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
        return content;
    }
    public static void main(String [] args) throws Exception{
       System.out.println(decode(new File("D:\\bill.pdf")));
       System.out.println(decode(new File("D:\\bill.png")));
    }
}
